import React, {useEffect, useRef, useState} from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import Scrollbar from "react-scrollbars-custom";
import {Button, Col, Form, Input, message, Row} from "antd";
import {PageContainer} from "@ant-design/pro-components";
import {create} from "@/services/ant-design-pro/api";

const Welcome: React.FC = () => {
  const scrollbarRef = useRef<Scrollbar>(null);
  let eventSource:EventSource;
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  useEffect(() => {
    return () => {
      if(eventSource){
        eventSource.close();
      }
    };
  }, []);
  useEffect(() => {
    if (scrollbarRef.current) {
      scrollbarRef.current.scrollToBottom();
    }
  }, [content]);

  const send=(messageId: string)=>{
    setLoading(true)
    setContent("");
    eventSource = new EventSource(
      'http://localhost:9902/api/message1?messageId='+messageId,
    );
    eventSource.onmessage = (event) => {
      let parse = JSON.parse(event.data);
      if(parse.finishReason==='stop'){
        message.success("生成完成").then();
        setLoading(false)
      }
      setContent((prevMessage) => prevMessage + parse.content);
    };
    eventSource.onopen = () => {
      console.log('Connection established');
    };
    eventSource.onerror = (error) => {
      console.error('EventSource failed:', error);
      eventSource.close();
      setLoading(false)
    };
  }


  return (
    <PageContainer title='评论生成器'>
      <Row gutter={16}>
        <Col span={8}>
          <Form form={form}>
            <Form.Item name='content' rules={[{required:true,message:'必填'}]}>
              <Input.TextArea disabled={loading} placeholder='文章内容' autoSize={{minRows:18,maxRows:18}} />
            </Form.Item>
            <Form.Item name='rule' rules={[{required:true,message:'必填'}]}>
              <Input.TextArea disabled={loading} placeholder='评论规则' autoSize={{minRows:4,maxRows:4}} />
            </Form.Item>
            <Form.Item name='rule'>
              <Button type="primary" loading={loading} block onClick={()=>{
                form.validateFields().then(formValues=>{
                  create(formValues).then((res)=>{
                    send(res.data);
                  })
                });
              }}>生成评论</Button>
            </Form.Item>
          </Form>
        </Col>
        <Col span={16}>
          <div style={{ height: window.innerHeight-110 }}>
            <Scrollbar ref={scrollbarRef} style={{height:window.innerHeight-110}}>
              <Markdown
                remarkPlugins={[remarkGfm]}
                components={{
                  h1: ({ node, ...props }) => (
                    <h1 style={{ fontSize: '2rem',fontWeight:'bold',marginTop: '0.67em', marginBottom: '0.67em' }} {...props} />
                  ),
                  h2: ({ node, ...props }) => (
                    <h2 style={{ fontSize: '1.5em',fontWeight:'bold',marginTop: '0.83em', marginBottom: '0.83em'  }} {...props} />
                  ),
                  h3: ({ node, ...props }) => (
                    <h3 style={{ fontSize: '1.17em',fontWeight:'bold',marginTop: '1em', marginBottom: '1em'  }} {...props} />
                  ),
                  h4: ({ node, ...props }) => (
                    <h4 style={{ fontSize: '1em',fontWeight:'bold',marginTop: '1.33em', marginBottom: '1.33em'  }} {...props} />
                  ),
                  h5: ({ node, ...props }) => (
                    <h5 style={{ fontSize: '0.83em',fontWeight:'bold',marginTop: '1.67em', marginBottom: '1.67em'  }} {...props} />
                  ),
                  h6: ({ node, ...props }) => (
                    <h6 style={{ fontSize: '0.75em',fontWeight:'bold',marginTop: '2.33em', marginBottom: '2.33em'  }} {...props} />
                  ),
                  ol: ({ node, ...props }) => (
                    <ol style={{ listStyle:'decimal', fontSize: '1em', lineHeight: '1.5',fontWeight:'normal',marginTop: '1em', marginBottom: '1em'  }} {...props} />
                  ),
                  li: ({ node, ...props }) => (
                    <li style={{ fontSize: '1em', lineHeight: '1.5',fontWeight:'normal',marginTop: '1em', marginBottom: '1em'  }} {...props} />
                  ),
                  p: ({ node, ...props }) => (
                    <p style={{ fontSize: '1rem', lineHeight: '1.5', fontWeight:'normal',marginTop: '1em', marginBottom: '1em' }} {...props} />
                  ),
                  code: ({ node, inline, className, children, ...props }) => {
                    return !inline ? (
                      <pre style={{ backgroundColor: '#f4f4f4', padding: '10px' }}>
                <code>{children}</code>
              </pre>
                    ) : (
                      <code style={{ backgroundColor: '#f4f4f4', padding: '2px 6px' }} {...props}>
                        {children}
                      </code>
                    );
                  },
                  a: ({ node, ...props }) => (
                    <a style={{ color: '#007bff', textDecoration: 'none' }} {...props} />
                  ),
                }}
              >
                {content}
              </Markdown>
            </Scrollbar>
          </div>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default Welcome;
